//
//  NSDictionary+UtilsExtras.m
//  SPay.base
//
//  Created by wongfish on 15/6/17.
//  Copyright (c) 2015年 wongfish. All rights reserved.
//

#import "NSDictionary+UtilsExtras.h"

@implementation NSDictionary (UtilsExtras)
#pragma mark - json转换
/**
 json字典转字符串
 @return 字符串
 */
- (NSString*)parseResponseJSONToString{
    
    NSError *error;
    NSData *jsonData;
    if ([NSJSONSerialization isValidJSONObject:self]) {
        jsonData = [NSJSONSerialization dataWithJSONObject:self
                                                   options:0
                                                     error:&error];
        if (jsonData != nil && error == nil) {
            return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
    }
    return nil;
}

/**
 *  字典转HTTP get参数
 */
- (NSString*)jsonToHttpGetParameter{
    NSString *aParameter = @"";
    for (NSInteger i=0; i < self.allKeys.count ; i++) {
        NSString *kStr = self.allKeys[i];
        NSString *val = [self objectForKey:kStr];
        if (i != 0) {
            aParameter = [NSString stringWithFormat:@"%@&%@=%@",aParameter,kStr,val];
        }else{
            aParameter = [NSString stringWithFormat:@"%@%@=%@",aParameter,kStr,val];
        }
    }
    return aParameter;
}

#pragma mark -  字典安全处理
/**
 判断字典中某个key是否存在
 @param keyName 健
 @return YES/NO
 */
- (BOOL)isForKeyExists:(NSString*)keyName{
    if ([[self allKeys] containsObject:keyName]) {
        return YES;
    }
    return NO;
}

/**
 判断字典中某个key是否存在
 @param keyName 健
 @return YES/NO
 */
- (id)safeObjectForKey:(NSString*)key{
    id val = [self objectForKey:key];
    if ([val isEqual:[NSNull null]]) {
        return nil;
    }
    return val;
}


#pragma mark - 排序
/**
 通过字典的key，以ASCII排序
 @return 数组
 */
- (NSArray*)orderForKeyAscii{
    NSArray *array = self.allKeys;
    
    //将表单内容的字段按照ASCII排序，排序规则为ASCII从小到大排序
    NSArray *orderArray =  [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return ([obj2 compare:obj1] == NSOrderedAscending);
    }];
    return orderArray;
}

@end

#pragma mark - NSMutableDictionary
@implementation NSMutableDictionary (SPayUtilsExtras)

#pragma mark - 字典安全处理
/**
 安全的对字典赋值
 @param anObject 值
 @param aKey 健
 */
- (void)safeSetObject:(id)anObject forKey:(id)aKey {
    if (anObject)
        [self setObject:anObject forKey:aKey];
}

@end
